package com.ycrlkj.android.modulespublic.common.net.transformer;

import androidx.annotation.NonNull;
import com.ycrlkj.android.modulespublic.common.net.exception.ApiException;
import com.ycrlkj.android.modulespublic.common.net.response.MResponse;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.functions.Function;

public class SyncCommonTransformer<T> implements ObservableTransformer<MResponse<T>, T> {

    public static <U> SyncCommonTransformer<U> obtain() {
        return new SyncCommonTransformer<>();
    }

    @NonNull
    @Override
    public ObservableSource<T> apply(Observable<MResponse<T>> upstream) {
        return upstream
                //错误处理
                .onErrorResumeNext(new Function<Throwable, ObservableSource<? extends MResponse<T>>>() {
                    @Override
                    public ObservableSource<? extends MResponse<T>> apply(Throwable throwable) throws Exception {
                        // 出现异常后统一处理
                        return Observable.error(ApiException.exception2ApiException(throwable));
                    }
                })
                //json转换
                .flatMap(new Function<MResponse<T>, ObservableSource<T>>() {
                    @Override
                    public ObservableSource<T> apply(@NonNull MResponse<T> response) throws Exception {
                        return new ResponseDataHandler<T>(response).doWith();
                    }
                });
    }
}
